package com.lechi.web.service.impl;

import com.lechi.web.common.enums.ErrorCodeEnum;
import com.lechi.web.common.exception.ServiceException;
import com.lechi.web.framework.log.IotExceptionLog;
import com.lechi.web.service.IIotDeviceTableService;
import com.lechi.web.system.mapper.iot.IotDeviceTableMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * 设备Service业务层处理
 *
 * @author yangguang
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class IotDeviceTableServiceImpl implements IIotDeviceTableService {

    private final IotDeviceTableMapper iotDeviceTableMapper;

    @Override
    public void createDeviceTable(String deviceTable) {
        try {
            iotDeviceTableMapper.createDeviceTable(deviceTable);
        } catch (Exception e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            CompletableFuture.runAsync(IotExceptionLog.exceptionLog(e, "创建设备表", method, deviceTable));
            throw new ServiceException(ErrorCodeEnum.ADD_ERROR.getValue(), ErrorCodeEnum.ADD_ERROR.getKey());
        }
    }

    @Async
    @Override
    public void dropDeviceTable(String deviceTable) {
        try {
            iotDeviceTableMapper.dropDeviceTable(deviceTable);
        } catch (Exception e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            CompletableFuture.runAsync(IotExceptionLog.exceptionLog(e, "删除设备表", method, deviceTable));
            throw new ServiceException(ErrorCodeEnum.DELETE_ERROR.getValue(), ErrorCodeEnum.DELETE_ERROR.getKey());
        }
    }
}
